package com.ahwei.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.ahwei.gateway.entity.TokenPayLoad;
import com.ahwei.gateway.util.JwtTokenUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 全局过滤器：需要实现GlobalFilter接口和Ordered接口
 * 用户认证过滤器
 * </p>
 *
 * @author ahWei
 * @email：ahwei163@qq.com
 * @since 2022-06-10 16:36:32
 */
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 令牌头的名字
     */
    private static final String AUTHORIZE_TOKEN = "Authorization";

    /**
     * 全局过滤
     *
     * @param exchange .
     * @param chain .
     * @return .
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 1. 获得token
        String jwtToken = request.getHeaders().getFirst(AUTHORIZE_TOKEN);

        // 2. 没有令牌，则拦截
        if (StrUtil.isEmpty(jwtToken)) {
            // 设置401状态码，提示用户没有权限，用户收到该提示后需要重定向到登陆页面
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应空数据
            return response.setComplete();
        }

        // 3. 从token中获取荷载
        try {
            // 获取Token
            jwtToken = jwtToken.replace("Bearer", "").trim();
            // 解析Token
            TokenPayLoad tokenPayLoad = JwtTokenUtil.verifyTokenByRSA(jwtToken);
            System.out.println(tokenPayLoad);

            // 令牌正常解析，为了方便在其他微服务进行认证，这里将用户名放入到请求头中
            request.mutate().header(AUTHORIZE_TOKEN, tokenPayLoad.getSub());
        } catch (Exception e) {
            // 无效令牌
            // 设置401状态码，提示用户没有权限，用户收到该提示后需要重定向到登陆页面
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应空数据
            return response.setComplete();
        }

        // 放行
        return chain.filter(exchange);
    }

    /**
     * 排序，越小越先执行
     *
     * @return .
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
